﻿using MesBSW.BLL;
using MesBSW.BLL.Mes;
using MesBSW.Tools;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace MesBSW.View.Mes
{
    public partial class AbnormalOrderIndexFrm : UIPage
    {
        #region 调用内部BLL层
        AbnormalOrderBLL abnormalOrderBLL = new AbnormalOrderBLL();
        #endregion

        private SqlSugarClient Db = SqlSugares.GetInstance();
        BaseControler bs = new BaseControler();
        private Timer timer = new Timer();
        public AbnormalOrderIndexFrm()
        {
            InitializeComponent();
            this.btnClear.FillColor = Color.AliceBlue;
            this.btnClear.ForeColor = Color.Black;
            DateTime today = DateTime.Today.AddDays(-7);
            DateTime endOfToday = today.AddDays(+9);
            this.PlayDate.Value = today;//开始时间
            this.EndDate.Value = endOfToday;//结束时间
            timer.Interval = 2000;
            timer.Tick += timer1_Tick;
            timer.Start();
        }

        /// <summary>
        /// 显示不良原因扇形图
        /// </summary>
        public void SelecrShowOrder()
        {
            List<int> deptIds = bs.SelectUserDept();
            string deptStr = "";
            for (int i = 0; i < deptIds.Count; i++)
            {
                deptStr += "'" + deptIds[i] + "'" + ",";
            }
            deptStr = deptStr.Substring(0, deptStr.Length - 1);
            Control controlToRemove = this.Controls.Find("Index", true).FirstOrDefault();
            if (controlToRemove != null)
            {
                this.Controls.Remove(controlToRemove);
                controlToRemove.Dispose();
            }
            //创建一个新的Chart控件11
            System.Windows.Forms.DataVisualization.Charting.Chart pieChart = new System.Windows.Forms.DataVisualization.Charting.Chart();
            //创建一个新的ChartArea
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea = new System.Windows.Forms.DataVisualization.Charting.ChartArea("chartArea");
            pieChart.ChartAreas.Add(chartArea);
            pieChart.Parent = this;
            pieChart.Size = new System.Drawing.Size(620, 580); //设置控件大小
            pieChart.Name = "Index";//给控件命名,下次进入就通过这个名字删除
            pieChart.Location = new System.Drawing.Point(1050, 323);
            //创建一个新的Series,并设置为 Pie 类型
            System.Windows.Forms.DataVisualization.Charting.Series series = new System.Windows.Forms.DataVisualization.Charting.Series();
            series.ChartType = SeriesChartType.Pie;
            series.IsValueShownAsLabel = false; // 设置为false，隐藏扇形图中间的文本
            pieChart.Series.Add(series);
            var list = Db.Context.SqlQueryable<object>($@"SELECT TOP 20
                reason_name,
                CAST(SUM(abnormal_qty) AS INT) AS abnormal_qty,
                COUNT(*) AS [count],
                CAST(ROUND((COUNT(*) * 100.0 / (SELECT COUNT(*) FROM abnormal_detail T1 left join target_prod_process T2 on T1.prod_number = T2.prod_number 
                WHERE T2.dept_id in ({deptStr}) and begin_time >= '{this.PlayDate.Value}' AND begin_time <= '{this.EndDate.Value}')), 2) AS DECIMAL(10, 2)) AS percentage
            FROM
                abnormal_detail T1 left join target_prod_process T2 on T1.prod_number = T2.prod_number 
            WHERE
               begin_time >='{this.PlayDate.Value}' AND begin_time <= '{this.EndDate.Value}' and T2.dept_id in ({deptStr})
            GROUP BY
                reason_name
            ORDER BY
                COUNT(*) DESC;").ToList();
            dynamic dylist = list;
            for (int i = 0; i < list.Count; i++)
            {
                series.Points.AddXY("", dylist[i].percentage);
                series.Points[i].Label = ""; // 清空扇形图中的数据显示
                series.Points[i].LegendText = $"{dylist[i].reason_name} {dylist[i].percentage}% 数量为：{dylist[i].abnormal_qty}"; // 设置右上角显示的数据
            }
            series["PieLabelStyle"] = "Inside";
            //显示图例
            System.Windows.Forms.DataVisualization.Charting.Legend legend = new System.Windows.Forms.DataVisualization.Charting.Legend();
            pieChart.Legends.Add(legend);
        }

        /// <summary>
        /// 显示不良率柱状图
        /// </summary>
        public void SelectNotGoodNumber()
        {
            List<int> deptIds = bs.SelectUserDept();
            string deptStr = "";
            for (int i = 0; i < deptIds.Count; i++)
            {
                deptStr += "'" + deptIds[i] + "'" + ",";
            }
            if(deptIds.Count==0)
            {
                deptStr ="0";
            }
            else
            {
                deptStr = deptStr.Substring(0, deptStr.Length - 1);
            }
            System.Data.DataTable list = Db.Context.SqlQueryable<Abnormal>($@"SELECT   top 100
	               T1.prod_number,
	               site_name,
	               reason_name,
	               abnormal_qty,
	               status_name,
                   begin_time,
                   end_time,
                   CASE
                       WHEN end_time IS NULL THEN '未处理'
                       ELSE '已处理'
                   END AS IsNullTime
                FROM 
                    abnormal_detail T1 left join target_prod_process T2 on T1.prod_number = T2.prod_number 
                where
	                begin_time >= '{this.PlayDate.Value}' and begin_time <= '{this.EndDate.Value}' and T2.dept_id in ({deptStr})
                ORDER BY 
                    status_name DESC, IsNullTime ASC").ToDataTable();
            list.Columns.Add("seq", typeof(int));
            // 为每一行的序号列赋值
            for (int i = 0; i < list.Rows.Count; i++)
            {
                list.Rows[i]["seq"] = i + 1;
            }
            this.dgvRepair.DataSource = list;
            string AvgTime = abnormalOrderBLL.AvgTime(this.PlayDate.Value.ToString(), this.EndDate.Value.ToString());//获取平均处理时间
            uiLabel4.Text = "平均处理时间：" + AvgTime;
            foreach (DataRow row in list.Rows)
            {
                //严重异常且未处理
                if (row.ItemArray[7].ToString() == "未处理" && row.ItemArray[4].ToString() == "严重异常")
                {
                    this.dgvRepair.Rows[row.Table.Rows.IndexOf(row)].DefaultCellStyle.ForeColor = Color.Red;
                }
                if (row.ItemArray[7].ToString() == "未处理" && row.ItemArray[4].ToString() == "普通异常")
                {
                    this.dgvRepair.Rows[row.Table.Rows.IndexOf(row)].DefaultCellStyle.ForeColor = Color.Blue;
                }
            }
            var list2 = Db.Context.SqlQueryable<object>($@"SELECT *
                FROM 
                    pp_scan
                where
	                scan_date >= '{this.PlayDate.Value}' and scan_date <= '{this.EndDate.Value}' and site_id = 24 ").ToList();
            if (list2.Count != 0 && list.Rows.Count != 0)
            {
                decimal d1 = list.Rows.Count.ObjToDecimal() / list2.Count.ObjToDecimal() * 100;
                d1 = Math.Round(d1, 2);
                this.uiLabel3.Text = "不良率：" + d1 + "%";
            }
            else
            {
                this.uiLabel3.Text = "不良率：";
            }
            #region 不跑了
            ////创建一个新的Chart控件
            //System.Windows.Forms.DataVisualization.Charting.Chart chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
            //chart1.Name = "SZT";
            //Control controlToRemove = this.Controls.Find("SZT", true).FirstOrDefault();
            //if (controlToRemove != null)
            //{
            //    this.Controls.Remove(controlToRemove);
            //    controlToRemove.Dispose();
            //}
            ////设置Chart控件的大小和位置
            //chart1.Size = new System.Drawing.Size(1200, 500);
            //chart1.Location = new System.Drawing.Point(0, 403);

            ////添加一个ChartArea
            //chart1.ChartAreas.Add("MainChartArea");
            ////添加一个数据系列
            //System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
            //series1.ChartArea = "MainChartArea";
            //chart1.Series.Add(series1);
            ////添加数据
            ////当天的23点59分
            //DateTime today = DateTime.Today;
            //string PlayDate = today.ToString("yyyy-MM-dd 00:00:00");
            //DateTime endOfToday = today.AddDays(1).AddMinutes(-1);
            //string EndDate = endOfToday.ToString("yyyy-MM-dd 23:59:59");
            //if (this.uiCBOTime.Text == "三天内")
            //{
            //    PlayDate = today.AddDays(-3).ToString("yyyy-MM-dd 00:00:00");
            //}
            //else
            //{
            //    PlayDate = today.AddDays(-7).ToString("yyyy-MM-dd 00:00:00");
            //}
            //var list = abnormalOrderBLL.SelectNotGoodNumber("", PlayDate, EndDate);
            //EndDate = endOfToday.AddDays(+1).ToString("yyyy-MM-dd");
            //string AvgTime = abnormalOrderBLL.AvgTime(PlayDate, EndDate);//获取平均处理时间
            //uiLabel4.Text = "平均处理时间：" + AvgTime;
            //dynamic dylist = list;
            //for (int i = 0; i < list.Count; i++)
            //{
            //    //添加数据
            //    series1.Points.AddXY(dylist[i].prod_number_with_status, dylist[i].abnormal_rate);
            //    series1.Points[i].Label = $"{dylist[i].site_name}";
            //}
            //series1.Color = Color.Red;
            //// 根据条件绘制不同的图形
            ////series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;//树形图
            //series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;//柱状图
            //// 将 Chart 控件添加到 Form 中
            //this.Controls.Add(chart1);
            #endregion
        }
        /// <summary>
        /// 点击查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiLabel1_Click(object sender, EventArgs e)
        {
            timer.Interval = 600000;
            timer.Tick += timer1_Tick;

            timer.Start();
        }
        /// <summary>
        /// 定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            SelecrShowOrder();
            
            SelectNotGoodNumber();
            //跑一遍后修改时间，十分钟刷新一次
            timer.Interval = 600000;
        }

        private class Abnormal
        {
            public string IsNullTime { get; set; }

            public string status_name { get; set; }

            public string prod_number { get; set; }

            public string site_name { get; set; }

            public decimal abnormal_qty { get; set; }
            public string reason_name { get; set; }
            public DateTime begin_time { get; set; }
            public DateTime end_time { get; set; }

        }

        private void dgvRepair_Sorted(object sender, EventArgs e)
        {
            // 获取DataGridView当前显示的数据
            System.Data.DataTable dt = new System.Data.DataTable();
            foreach (DataGridViewColumn col in dgvRepair.Columns)
            {
                dt.Columns.Add(col.HeaderText);
            }

            foreach (DataGridViewRow row in dgvRepair.Rows)
            {
                DataRow dRow = dt.NewRow();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dRow[cell.ColumnIndex] = cell.Value;
                }
                dt.Rows.Add(dRow);
            }

            foreach (DataRow row in dt.Rows)
            {
                //严重异常且未处理
                if (row.ItemArray[7].ToString() == "未处理" && row.ItemArray[4].ToString() == "严重异常")
                {
                    this.dgvRepair.Rows[row.Table.Rows.IndexOf(row)].DefaultCellStyle.ForeColor = Color.Red;
                }
                if (row.ItemArray[7].ToString() == "未处理" && row.ItemArray[4].ToString() == "普通异常")
                {
                    this.dgvRepair.Rows[row.Table.Rows.IndexOf(row)].DefaultCellStyle.ForeColor = Color.Blue;
                }
            }
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClear_Click(object sender, EventArgs e)
        {
            SelecrShowOrder();
            SelectNotGoodNumber();
        }
    }
}
